package comptadub

import java.awt.PageAttributes.OrientationRequestedType;

class LigneCompteController {

    def exportService
    def membreService
    def compteService
    
    static allowedMethods = [index: "POST", save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        flash.objet = params.objet
        flash.membre = params.membre
        flash.type = params.type

        if (!params.max) params.max = 10
        if (!params.sort) params.sort = "id"
        if (!params.order) params.order = "desc"

        if (!flash.membre) flash.membre = session.idMembre.toString()
        if (!flash.type) flash.type = '0'

        def query = {
            and {
                if (flash.objet) {
                    like("objet", '%' + flash.objet + '%')
                }
                if (flash.type != '0') {
					if (flash.type != '9') {
	                    typeLigne {
		                    eq("code", flash.type)
	                    }
					}
                } else {
					typeLigne {
						or {
							eq("code", "ndf")
							eq("code", "pres")
						}
					}
                }
                if (flash.membre != '0') {
                    def selMembre = Membre.get(flash.membre.toInteger())
                    eq("membre", selMembre)
                }
            }
        }

        def criteria = LigneCompte.createCriteria()
        def results = criteria.list(params, query)
        
        [ ligneCompteInstanceList: results ]
    }

    def export = {
        flash.objet = params.objet
        flash.membre = params.membre
        flash.type = params.type
        params.max = null
        params.offset = null

        if (!params.sort) params.sort = "id"
        if (!params.order) params.order = "desc"

        def query = {
            and {
                if (flash.objet) {
                    like("objet", '%' + flash.objet + '%')
                }
                if (flash.type != '0') {
                    typeLigne {
                        eq("id", flash.type.toLong())
                    }
                }
                if (flash.membre != '0') {
                    def selMembre = Membre.get(flash.membre.toInteger())
                    eq("membre", selMembre)
                }
            }
        }

        def criteria = LigneCompte.createCriteria()
        def results = criteria.list(params, query)

        if(params?.format && params.format != "html")
        {
            response.contentType =  grailsApplication.config.grails.mime.types[params.format] //ConfigurationHolder.config.grails.mime.types[params.format]
            response.setHeader("Content-disposition", "attachment; filename=comptes.${params.extension}")
            List fields = ["membre.nom", "date", "credit", "debit", "typeLigne.nom", "objet", "commentaire"]
            Map labels = ["membre.nom": "membre", "typeLigne.nom": "type"]
            exportService.export(params.format, response.outputStream, results, fields, labels, [:], [:])
        }
    }

    def listAutre = {
        flash.objet = params.objet
        flash.membre = params.membre

        if (!params.max) params.max = 10
        if (!params.sort) params.sort = "id"
        if (!params.order) params.order = "desc"
		
        if(!flash.membre) flash.membre = session.idMembre.toString()

        def query = {
            and {
                typeLigne {
                    eq("code", "autre")
                }
                if (flash.objet) {
                    like("objet", '%' + flash.objet + '%')
                }                
                if (flash.membre != '0') {
                    def selMembre = Membre.get(flash.membre.toInteger())
                    eq("membre", selMembre)
                }
            }
        }

        def criteria = LigneCompte.createCriteria()
        def results = criteria.list(params, query)

        [ ligneCompteInstanceList: results ]
    }

    def exportAutre = {
        flash.objet = params.objet
        flash.membre = params.membre
        params.max = null
        params.offset = null

        if(!flash.membre) {
            flash.membre = session.idMembre.toString()
        }

        def query = {
            and {
                typeLigne {
                    eq("code", "autre")
                }
                if (flash.objet) {
                    like("objet", '%' + flash.objet + '%')
                }
                if (flash.membre != '0') {
                    def selMembre = Membre.get(flash.membre.toInteger())
                    eq("membre", selMembre)
                }
            }
        }

        def criteria = LigneCompte.createCriteria()
        def results = criteria.list(params, query)

        if(params?.format && params.format != "html")
        {
            response.contentType = grailsApplication.config.grails.mime.types[params.format] //ConfigurationHolder.config.grails.mime.types[params.format]
            response.setHeader("Content-disposition", "attachment; filename=comptes.${params.extension}")
            List fields = ["membre.nom", "date", "credit", "debit", "typeLigne.nom", "objet", "commentaire"]
            Map labels = ["membre.nom": "membre", "typeLigne.nom": "type"]
            exportService.export(params.format, response.outputStream, results, fields, labels, [:], [:])
        }
    }

    def create = {
        def ligneCompteInstance = new LigneCompte()
        ligneCompteInstance.membre = Membre.get(session.idMembre.toString())
        ligneCompteInstance.properties = params
        return [ligneCompteInstance: ligneCompteInstance]
    }

    def save = {
        def ligneCompteInstance = new LigneCompte(params)
        compteService.definirObjet(ligneCompteInstance)

        if (ligneCompteInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'ligneCompte.label', default: 'LigneCompte'), ligneCompteInstance.id])}"
            membreService.calculerSolde(ligneCompteInstance.membre?.id)
            redirect(action: "show", id: ligneCompteInstance.id)
        }
        else {
            render(view: "create", model: [ligneCompteInstance: ligneCompteInstance])
        }
    }

    def show = {
        def ligneCompteInstance = LigneCompte.get(params.id)
        if (!ligneCompteInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'ligneCompte.label', default: 'LigneCompte'), params.id])}"
            redirect(action: "list")
        }
        else {
            if (ligneCompteInstance.typeLigne?.code == "ndf") {
                redirect(controller:"noteDeFrais", action: "show", id: ligneCompteInstance.id)
            } else if (ligneCompteInstance.typeLigne?.code == "pmt") {
                redirect(controller:"paiement", action: "show", id: ligneCompteInstance.id)
            } else if (ligneCompteInstance.typeLigne?.code == "pres") {
                redirect(controller:"presence", action: "show", id: ligneCompteInstance.id)
            } else {
                return [ligneCompteInstance: ligneCompteInstance]
            }
        }
    }

    def edit = {
        def ligneCompteInstance = LigneCompte.get(params.id)
        if (!ligneCompteInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'ligneCompte.label', default: 'LigneCompte'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [ligneCompteInstance: ligneCompteInstance]
        }
    }

    def update = {
        def ligneCompteInstance = LigneCompte.get(params.id)
        if (ligneCompteInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (ligneCompteInstance.version > version) {
                    
                    ligneCompteInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'ligneCompte.label', default: 'LigneCompte')] as Object[], "Another user has updated this LigneCompte while you were editing")
                    render(view: "edit", model: [ligneCompteInstance: ligneCompteInstance])
                    return
                }
            }
            ligneCompteInstance.properties = params
            compteService.definirObjet(ligneCompteInstance)

            if (!ligneCompteInstance.hasErrors() && ligneCompteInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'ligneCompte.label', default: 'LigneCompte'), ligneCompteInstance.id])}"
                membreService.calculerSolde(ligneCompteInstance.membre?.id)
                redirect(action: "show", id: ligneCompteInstance.id)
            }
            else {
                render(view: "edit", model: [ligneCompteInstance: ligneCompteInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'ligneCompte.label', default: 'LigneCompte'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def ligneCompteInstance = LigneCompte.get(params.id)
        if (ligneCompteInstance) {
            try {
                ligneCompteInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'ligneCompte.label', default: 'LigneCompte'), params.id])}"
                membreService.calculerSolde(ligneCompteInstance.membre?.id)
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'ligneCompte.label', default: 'LigneCompte'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'ligneCompte.label', default: 'LigneCompte'), params.id])}"
            redirect(action: "list")
        }
    }
}
